package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    long BEGIN_STAMP = 1640995200L;

    public long nextId(String prefix){
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowsec = now.toEpochSecond(ZoneOffset.UTC);
        long timtstamp = nowsec - BEGIN_STAMP;
        // 生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yy:MM:dd"));

        long count = stringRedisTemplate.opsForValue().increment("icr"+prefix+":"+date);

        // 拼接并返回
        return timtstamp << 32 | count ;
    }
}
